package app;


import java.io.IOException;
import javax.wireless.messaging.Message;
import javax.wireless.messaging.MessageConnection;

/**
 *
 * @author thirdy
 */
// Isolate blocking I/O on a separate thread, so callback
// can return immediately.
class ThesisMessageReader implements Runnable {

    private int pendingMessages = 0;
    private boolean done = false;
    private MessageConnection messconn;
    private ThesisMessageReceiver thesisMessageReceiver;

    public ThesisMessageReader(MessageConnection messconn, ThesisMessageReceiver thesisMessageReceiver) {
        this.messconn = messconn;
        this.thesisMessageReceiver = thesisMessageReceiver;
    }

    // The run method performs the actual message reading.
    public void run() {
        while (!done) {
            synchronized (this) {
                if (pendingMessages == 0) {
                    try {
                        wait();
                    } catch (Exception e) {
                    }
                }
                pendingMessages--;
            }
            try {
                Message mess = messconn.receive();
                thesisMessageReceiver.messageReceived(mess);
            } catch (IOException ioe) {
                // TODO
            }
        }
    }

    public synchronized void handleMessage() {
        pendingMessages++;
        notify();
    }

    void close() {
        done = true;
    }

}
